/**
 * 系统用户修改js
 */
var comValidform=null;
var returnStatus=false;
var sysUserUpdate={
	dataCache:null,
	duties:null,
	userId:null,
	
	bindChangeDept:function(val){
	},
	
	startEvent:function(){
		//根据选择的离职状态改变离职时间
		$(".onType").on("change",function () {
            $("#vaildLeaveTime").attr("nullmsg","离职状态下，离职时间不能为空！");
			if($(this).val()==0){ //在职
				$("#vaildLeaveTime").val("1");
				$(".leaveTime").val("");
			}else if($(this).val()==1 && $(".leaveTime").val() !=""){
				$("#vaildLeaveTime").val("1");
			}else {
                $("#vaildLeaveTime").val("");
			}
        });
        $(".leaveTime").on("focusout",function () {
        	if($(this).val() !="" && $(".onType").val()==0){
                $("#vaildLeaveTime").attr("nullmsg","在职状态下，离职时间要为空！");
                $("#vaildLeaveTime").val("");
			}else if($(this).val() =="" && $(".onType").val()==1){
                $("#vaildLeaveTime").attr("nullmsg","离职状态下，离职时间不能为空！");
                $("#vaildLeaveTime").val("");
			}else{
                $("#vaildLeaveTime").val("1");
			}
        });
		
		//获取所有职务
		var url = 'mgr/OrganizationCtrl/listAll';
		var params = null;

		var cb = function(data) {
			console.trace("data code = " & data.resultCode);
			if (data.resultCode == 200) {
				sysUserUpdate.duties = data.result;
			}
		};
		
		sendApiNoLoadSync(url, params, cb, 'GET');
		
		//展现职务
		sysUserUpdate.showInfoById();
		
		//更改职务提交
		comValidform=$(".com-addForm").Validform({
			tiptype:2,
			tipSweep:true,
			beforeSubmit:function(curform){
				var checkedId='';
				$('.com-addForm').find('input:checkbox[name="roleList"]:checked').each(function(){
					var checkedVal=$(this).val();
					checkedId+=checkedVal.split(':')[0]+',';
				});

				if(checkedId!=''){
					checkedId=checkedId.substring(0,checkedId.length-1);
					$('.com-addForm input[name="sysRoleIds"]').val(checkedId);
				}else{
					$('.com-addForm input[name="sysRoleIds"]').val(null);
				}


				
				var url = 'mgr/SysUserCtrl/updateSysUser';
				var params = jsUtils.serializeJson($('.com-addForm'));
				params.actUserId = userId;
				delete params.roleList;

                if(params.entryTime == null || params.entryTime == ''){
                    delete params.entryTime;
                }
                if(params.leaveTime == null || params.leaveTime == ''){
                	delete params.leaveTime;
				}


                var updateIFAtrace = art.dialog.data('updateIFAtrace');
                var changeIFA = $('.com-addForm select[name="isInside"]').val();
                art.dialog.data('updateIFAtrace',updateIFAtrace+changeIFA);

				var cb = function(data){
					alert(data.msg);
					//成功返回
					if(data.resultCode==200){
						//关闭窗口并刷新数据
						//art.dialog.close();
                        localStorage.removeItem(sysUserUpdate.id);
                        var singleObj = data.result;

                        localStorage.setItem(singleObj.id
                            + "_User_Key", JSON
                            .stringify(singleObj));
						returnStatus=true;
					}
				};
				sendApiNoLoadSync(url, params, cb, 'POST');
				return returnStatus;
			}
		});

	},
	showDuties:function(){
		var setting = {
				check : {
					enable : true,
					chkStyle : "radio",
					radioType : "all"
				},
				data : {
					simpleData : {
						enable : true
					}
				},
				view : {
					nameIsHTML : true
				},
				callback : {
					onCheck : zTreeOnClick,
					beforeCheck: zTreeBeforeCheck
				}
			};
			var zNodes = [];
			var duties = sysUserUpdate.duties;
			
			var orgId=$('#com-addForm input[name="orgId"]').val();
			for (var i = 0; i < duties.length; i++) {
				zNodes[i] = {
					id : duties[i].id,
					name : duties[i].name,
					pId : duties[i].parentID
				};
				if (i == 0) {
					zNodes[i].open = true;
				}
				
				if(orgId == duties[i].id){
					zNodes[i].checked=true;
				};
			}
			$.fn.zTree.init($("#dutTree"), setting, zNodes);
	},
	showRole:function(){
		//获取所有角色
		var url ='mgr/SysRoleCtrl/getSysRoleList';
		var params={
			'curPage':0,
			'pageSize':9999
		};
		var cb = function(data){
			sysUserUpdate.dataCache=data.result;
			var rolesCache=sysUserUpdate.dataCache;
			var tr='';
			for(var i=0;i<rolesCache.length;i++){
				if(i%4==0){
					tr+='<tr style="height: 25px;">';
				}
				var id=rolesCache[i].sysRole.id;
				var name=rolesCache[i].sysRole.name;
				tr+='<td><input type="checkbox" name="roleList" value="'+id+':'+name+'" />'+name+'</td>';
				if(i%4==3){
					tr+='</tr>';
				}
			}
			$('#roleTable').append(tr);
			
			var checkedVal=$('#com-addForm input[name="sysRoleIds"]').val();
			var selectDiv=$('#roleTable');
			if(checkedVal!=''){
				if(checkedVal.indexOf(',')!=-1){
					var checkedVals=checkedVal.split(',');
					for(var i=0;i<checkedVals.length;i++){
						selectDiv.find('input:checkbox[name="roleList"]').each(function(){
							if(checkedVals[i]==$(this).val().split(':')[0]){
								$(this).prop('checked',true);
							}
						});
					}
				}else{
					selectDiv.find('input:checkbox[name="roleList"]').each(function(){
						if(checkedVal==$(this).val().split(':')[0]){
							$(this).prop('checked',true);
						}
					});
				}	
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');
	},
	
	showInfoById:function(){
		var updId=art.dialog.data('updId');  //修改id
        sysUserUpdate.id = updId+"_User_Key";
        var ret = eval('(' + localStorage.getItem(sysUserUpdate.id) + ')');
        for(var i in ret){
            var text=ret[i];
            if(i=='entryTime'||i=='leaveTime'||i=='birthday'){
                text=text==null?'':(new Date(text)).format('yyyy-MM-dd');
            }else if(i=='level'||i=='isInside' || i=='onType' || i=="closeAccount"){

                $('#com-addForm select[name="'+i+'"]').val(text);
            }

            $('#com-addForm input[name="'+i+'"]').val(text);

            if(i=='isInside'){
                art.dialog.data('updateIFAtrace',text);
            }
        }
        var roleId='';
        var userRoleCache=ret.sysUserRoleList;
        if(userRoleCache != null){
            for(var i=0;i<userRoleCache.length;i++){

                roleId+=userRoleCache[i].roleId+',';
            }
            if(roleId != null){
                $('#com-addForm input[name="sysRoleIds"]').val(roleId);
            }
        }

        sysUserUpdate.showDuties();
        sysUserUpdate.showRole();

	},
	
	init:function(){
		sysUserUpdate.startEvent();
	}
}
$(document).ready(function() {
	sysUserUpdate.init();
});
function submitForm(){
	comValidform.submitForm();
	return returnStatus;
}

function zTreeOnClick(event, treeId, treeNode) {
	$("#orgId").val(treeNode.id);
};

function zTreeBeforeCheck(treeId, treeNode, clickFlag) {
	if(treeNode.isParent){
		alert("请选择具体的职务！");
	}
	return !treeNode.isParent;//当是父节点 返回false 不让选取
}; 